<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../lib/bootstrap.css">
    <script src="../lib/jquery.min.js"></script>
</head>

<body>
    <input type="file" id="file1">
    <button id="btnUpLoad">上传文件</button>
    <div class="progress">
        <div class="progress-bar progress-bar-striped active" style="width:0%" id="percent">
            0%
        </div>
    </div>
    <br>
    <img src="" alt="" id="img" width="800">

    <script>
        let btn = document.querySelector("#btnUpLoad");
        btn.addEventListener("click", function () {
            let files = document.querySelector("#file1").files;

            if (files.length <= 0) {
                return alert("上传");
            }

            let fd = new FormData();
            fd.append("avatar", files[0]);

            let xhr = new XMLHttpRequest();
            //监听上传进度
            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    //计算进度
                    let process = Math.ceil((e.loaded / e.total) * 100);

                    $("#percent").attr("style", "width:" + process + "%").html(process + "%");
                }
            }

            xhr.upload.onload = function () {
                $("#percent").removeClass().addClass("progress-bar progress-bar-success");
            }

            xhr.open("POST", "http://www.liulongbin.top:3006/api/upload/avatar");
            xhr.send(fd);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    let data = JSON.parse(xhr.responseText);

                    if (data.status === 200) {
                        document.querySelector("#img").src = "http://www.liulongbin.top:3006" + data.url;
                    }
                    else {
                        console.log(data.message);
                    }
                }
            }
        })
    </script>
</body>

</html>